﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Niaofei.Injcetion;
using System.Net;
using System.Text;
using System.Text.Json;

namespace Niaofei.Web.Authorize
{
    [Injection(typeof(CustomJwtBearerEvents))]
    public class CustomJwtBearerEvents : JwtBearerEvents
    {
        public override async Task AuthenticationFailed(AuthenticationFailedContext context)
        {
            context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            context.Response.ContentType = "application/json";

            // 构建自定义的错误消息
            var errorMessage = "Authentication failed: " + context.Exception.Message;

            // 将错误消息写入响应体
            var body = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new { error = errorMessage }));
            await context.Response.Body.WriteAsync(body, 0, body.Length);

            // 停止继续处理请求
            context.Fail(errorMessage);
        }
    }
}
